var AV = require('leanengine');
var async = require('async');
//订单有关的模型
var orderM = require('../models/order');
var cartM = require('../models/cart.js');
var addrM = require('../models/address.js');
var UserM = require('../models/modUser.js');
var AddrM = require('../models/address');
var CouponM = require('../models/coupon');
var commonM = require('../models/common');
var productM = require('../models/product');

var FlowM = AV.Object.extend("OrderFlow");
var AmountFlowM = AV.Object.extend("AmountFlow");



module.exports = {

    getOrderListByAll:function(req,res,next){
        //我的全部订单 at 12.16 08:58 James
        var userid = req.AV.user.id;              //获取用户编号

        orderM.getOrderListByAll(userid).then(function(order){
            res.render('order/myOrderByAll',{title:'我的全部订单',order:order});
        }).catch(function(err){
            res.error(err);
        });
    },
    getOrderListByPay:function(req,res,next){
        //我的待付款订单
        var userid = req.AV.user.id;              //获取用户编号

        orderM.getOrderListByAll(userid).then(function(order){
            res.render('order/myOrderByPay',{title:'我的待付款订单',order:order});
        }).catch(function(err){
            res.error(err);
        });

    },
    getOrderListByReceived:function(req,res,next){
        //我的待收货订单
        var userid = req.AV.user.id;              //获取用户编号

        async.waterfall([
            //通过cname获取cid
            function(callback){
                ClzM.getByName(cname).then(function(clz){
                    callback(null,clz);
                });
            },
            //通过cid获取商品列表
            //clz 指向前面一个函数的输出值
            function(clz,callback){
                ProM.list(clz.id,page).then(function(list){
                    callback(null,{classify:clz,list:list});
                }).catch(function(err){
                    //TODO:错误的处理
                });
            }
        ],function(err,result){
            if(err){
                //TODO:
                return;
            }

            res.render('order/myOrderByReceived',{title:result.classify.get('intro'),list:result.list});
        });

    },
    getOrderListByEvaluation:function(req,res,next){
        //我的待评价订单
        var userid = req.AV.user.id;              //获取用户编号

        async.waterfall([
            //通过cname获取cid
            function(callback){
                ClzM.getByName(cname).then(function(clz){
                    callback(null,clz);
                });
            },
            //通过cid获取商品列表
            //clz 指向前面一个函数的输出值
            function(clz,callback){
                ProM.list(clz.id,page).then(function(list){
                    callback(null,{classify:clz,list:list});
                }).catch(function(err){
                    //TODO:错误的处理
                });
            }
        ],function(err,result){
            if(err){
                //TODO:
                return;
            }

            res.render('order/myOrderByEvaluation',{title:result.classify.get('intro'),list:result.list});
        });

    },
    getOrderListByComplete:function(req,res,next){
        //我的已完成订单
        var userid = req.AV.user.id;              //获取用户编号

        async.waterfall([
            //通过cname获取cid
            function(callback){
                ClzM.getByName(cname).then(function(clz){
                    callback(null,clz);
                });
            },
            //通过cid获取商品列表
            //clz 指向前面一个函数的输出值
            function(clz,callback){
                ProM.list(clz.id,page).then(function(list){
                    callback(null,{classify:clz,list:list});
                }).catch(function(err){
                    //TODO:错误的处理
                });
            }
        ],function(err,result){
            if(err){
                //TODO:
                return;
            }

            res.render('order/myOrderByComplete',{title:result.classify.get('intro'),list:result.list});
        });
    },
    /**
     * 跳转到确认订单页面
     * Created by James at 2015-09-07
     * @param req
     * @param res
     * @param next
     */
    confirmOrder:function(req,res,next){

        var userid = req.AV.user.id;              // 用户编号
        var openid = req.AV.user.get('openid');   // 用户openid
        var aid = req.params.aid;                 // 用户地址编号
        var total = 0;                            // 订单总金额
        var goods = [];                           // 订单商品
        var str = "";                             // 平台活动
        var level_rate = 1;                       // 用户等级打折率
        var dzje = 0;                             // 订单打折金额
        var fdzje = 0;                            // 订单非打折金额
        var bq_flag = 0;                          // 订单必抢标识
        var points = 0;

        if(aid == 0){
            //用户地址为空，代表是从购物车模块跳转过来的
            AddrM.listAddress(userid).then(function(obj){
                if(obj.length == 0){
                    //没有地址，则跳转到新增地址页面
                    var url = '/order/confirmOrder/';
                    res.redirect('/user/center/address?back='+url);
                }else{
                    async.waterfall([
                        //通过userid获取用户订单的商品
                        function(callback){
                            cartM.getProductList(userid,true).then(function(result){
                                var psid;
                                var cid;
                                var specArray;
                                var imgArray;
                                if (result.rows > 0) {
                                    for (x in result.data) {
                                        psid = result.data[x].get('psid'); //读取购物车单条数据的商品规格ID
                                        cid = result.data[x].get('product').get('cid');
                                        specArray = result.data[x].get('product').get('spec'); //读取商品规格数组
                                        imgArray = JSON.parse(result.data[x].get('product').get('picurlarray'));//读取商品图片数组
                                        goods.push(
                                            {
                                                pid:        result.data[x].get('pid'),
                                                pname:      result.data[x].get('product').get('name'),
                                                sid:        result.data[x].get('psid'),
                                                cid:        cid,
                                                sname:      specArray[psid]['name'],
                                                price:      parseInt(specArray[psid]['grprice']),
                                                size:       parseInt(result.data[x].get('number')),
                                                img:        imgArray[0],
                                                point:      specArray[psid]['point'],
                                                pointRate:  specArray[psid]['pointRate'],
                                                isPoint:    specArray[psid]['isPoint'],
                                                isDiscount: specArray[psid]['isDiscount']
                                            }
                                        )

                                        points = points+(parseInt(specArray[psid]['point']) * parseInt(result.data[x].get('number')));

                                        if(cid == 16){
                                            bq_flag = 1;
                                        }

                                        if(specArray[psid]['isDiscount'] == '1'){
                                            dzje = dzje + (parseInt(specArray[psid]['grprice']) * parseInt(result.data[x].get('number')));
                                        }

                                        if(specArray[psid]['isDiscount'] == '0'){
                                            fdzje = fdzje + (parseInt(specArray[psid]['grprice']) * parseInt(result.data[x].get('number')));
                                        }
                                    }
                                }
                                callback(null);
                            });
                        },
                        //获取购物车商品总价
                        function(callback){
                            cartM.getGoodsPrice(userid).then(function (result) {
                                total = result.GoodsPrice;
                                callback(null);
                            }).catch(function(err){
                                callback({code:9999,reason:err});   //code:9999 系统错误
                            });
                        },
                        //获取平台活动
                        function(callback){
                            cartM.getActivityRuleMJ(total).then(function (result) {
                                for (x in result.ruleList) {
                                    if(result.ruleList[x].get('checked') == true){
                                        str = result.ruleList[x].get('name');
                                    }
                                }
                                var discountPrice=result.discountPrice;
                                callback(null,discountPrice);
                            }).catch(function(err){
                                callback({code:9999,reason:err});   //code:9999 系统错误
                            });
                        },
                        //获取用户余额
                        function(discountPrice,callback){
                            UserM.getAmountByOpenID(openid).then(function (result) {
                                callback(null,discountPrice,result);
                            }).catch(function(err){
                                callback({code:9999,reason:err});   //code:9999 系统错误
                            });
                        },
                        //获取用户等级
                        function(discountPrice,balance,callback){
                            UserM.getLevelByOpenID(openid).then(function (level_id){
                                if(level_id == 2){
                                    level_rate = 1;
                                }else if(level_id == 3){
                                    level_rate = 0.95;
                                }else if(level_id == 4){
                                    level_rate = 0.92;
                                }else if(level_id == 5){
                                    level_rate = 0.9;
                                }else if(level_id == 1){
                                    level_rate = 0.85;
                                }
                                callback(null,{cartList:goods,total:total,dzje:dzje,fdzje:fdzje,discountPrice:discountPrice,str:str,level_rate:level_rate,balance:balance});
                            }).catch(function(err){
                                callback({code:9999,reason:err});   //code:9999 系统错误
                            });
                        }
                    ],function(err,result){
                        if(err){
                            res.error(err);
                        }
                        if(result.cartList.length == 0){
                            //如果没有商品，则跳转到首页
                            res.redirect('/');
                        }else{
                            res.render('order/confirmOrder',{title:'确认订单',cart:result.cartList,level_rate:result.level_rate,total:result.total,dzje:result.dzje,fdzje:result.fdzje,discountPrice:result.discountPrice,str:result.str,balance:result.balance,aid:aid,bq_flag:bq_flag,points:points});
                        }
                    });
                }
            }).catch(function(err){
                res.error(err);
            });
        }else{
            //用户地址不为空，代表是从我的地址模块跳转过来的
            async.waterfall([
                //通过userid获取用户订单的商品
                function(callback){
                    cartM.getProductList(userid,true).then(function(result){
                        var psid;
                        var cid;
                        var specArray;
                        var imgArray;
                        if (result.rows > 0) {
                            for (x in result.data) {
                                psid = result.data[x].get('psid'); //读取购物车单条数据的商品规格ID
                                cid = result.data[x].get('product').get('cid');
                                specArray = result.data[x].get('product').get('spec'); //读取商品规格数组
                                imgArray = JSON.parse(result.data[x].get('product').get('picurlarray'));//读取商品图片数组
                                goods.push(
                                    {
                                        pid:        result.data[x].get('pid'),
                                        pname:      result.data[x].get('product').get('name'),
                                        sid:        result.data[x].get('psid'),
                                        cid:        cid,
                                        sname:      specArray[psid]['name'],
                                        price:      parseInt(specArray[psid]['grprice']),
                                        size:       parseInt(result.data[x].get('number')),
                                        img:        imgArray[0],
                                        point:      specArray[psid]['point'],
                                        pointRate:  specArray[psid]['pointRate'],
                                        isPoint:    specArray[psid]['isPoint'],
                                        isDiscount: specArray[psid]['isDiscount']
                                    }
                                )

                                points = points+(parseInt(specArray[psid]['point']) * parseInt(result.data[x].get('number')));

                                if(cid == 16){
                                    bq_flag = 1;
                                }

                                if(specArray[psid]['isDiscount'] == '1'){
                                    dzje = dzje + (parseInt(specArray[psid]['grprice']) * parseInt(result.data[x].get('number')));
                                }

                                if(specArray[psid]['isDiscount'] == '0'){
                                    fdzje = fdzje + (parseInt(specArray[psid]['grprice']) * parseInt(result.data[x].get('number')));
                                }
                            }
                        }
                        callback(null);
                    });
                },
                //获取购物车商品总价
                function(callback){
                    cartM.getGoodsPrice(userid).then(function (result) {
                        total = result.GoodsPrice;
                        callback(null);
                    }).catch(function(err){
                        callback({code:9999,reason:err});   //code:9999 系统错误
                    });
                },
                //获取平台活动
                function(callback){
                    cartM.getActivityRuleMJ(total).then(function (result) {
                        for (x in result.ruleList) {
                            if(result.ruleList[x].get('checked') == true){
                                str = result.ruleList[x].get('name');
                            }
                        }
                        var discountPrice=result.discountPrice;
                        callback(null,discountPrice);
                    }).catch(function(err){
                        callback({code:9999,reason:err});   //code:9999 系统错误
                    });
                },
                //获取用户余额
                function(discountPrice,callback){
                    UserM.getAmountByOpenID(openid).then(function (result) {
                        callback(null,discountPrice,result);
                    }).catch(function(err){
                        callback({code:9999,reason:err});   //code:9999 系统错误
                    });
                },
                //获取用户等级
                function(discountPrice,balance,callback){
                    UserM.getLevelByOpenID(openid).then(function (level_id){
                        if(level_id == 2){
                            level_rate = 1;
                        }else if(level_id == 3){
                            level_rate = 0.95;
                        }else if(level_id == 4){
                            level_rate = 0.92;
                        }else if(level_id == 5){
                            level_rate = 0.9;
                        }else if(level_id == 1){
                            level_rate = 0.85;
                        }
                        callback(null,{cartList:goods,total:total,dzje:dzje,fdzje:fdzje,discountPrice:discountPrice,str:str,level_rate:level_rate,balance:balance});
                    }).catch(function(err){
                        callback({code:9999,reason:err});   //code:9999 系统错误
                    });
                }
            ],function(err,result){
                if(err){
                    res.error(err);
                }

                if(result.cartList.length == 0){
                    //如果没有商品，则跳转到首页
                    res.redirect('/');
                }else{
                    res.render('order/confirmOrder',{title:'确认订单',cart:result.cartList,level_rate:result.level_rate,total:result.total,dzje:result.dzje,fdzje:result.fdzje,discountPrice:result.discountPrice,str:result.str,balance:result.balance,aid:aid,bq_flag:bq_flag,points:points});
                }
            });
        }
    },
    confirmOrderUI:function(req,res,next){
        //确认订单
        res.render('order/confirmOrder',{title:'确认订单'});
    },
    /**
     * 生成订单
     * Created by James at 2015-09-07
     * @param req
     * @param res
     * @param next
     */
    addOrder:function(req,res,next){
        var data = req.query;//获取表单参数

        var par = data.par;

        delete data.par;

        var finalAmount = parseFloat(data.finalAmount);
        var total = parseFloat(data.total);
        var payway = data.payway;
        var couponId = data.couponId;
        var type = 0;           //0:普通订单 5：预售订单 6:外卖订单
        var code = "";         //商品活动标题简码
        var str ;
        var balance = 0;
        var online = 0;
        var onlinetype = '';
        var status = 1000;

        if(payway =='ye_pay'){
            str = '余额支付';
            balance = finalAmount;
            status = 2000;

        }else if(payway =='wx_pay'){
            str = '微信支付';
            online = finalAmount;
            onlinetype = '微信支付';
            status = 1000;
        }else{
            //payway =='hdfk_pay'
            str = '货到付款';
            status = 2000;
        }

        var uid = req.AV.user.id;
        var goods = new Array();
        var goods1 = new Array();
        var goods2 = new Array();
        var goods3 = new Array();
        var timestamp = new Date().getTime();
        var orderid = '';
        var order_id = 'O'+timestamp;
        var takeout = new Array();
        var points1 = 0;
        var points2 = 0;
        var dzje1 = 0;
        var dzje2 = 0;
        var je0 = 0;
        var je1 = 0;
        var yxRebate1 = 0;           //营销提成
        var yxRebate2 = 0;           //营销提成

        if(global.initData.takeout.takeout != 'undefined' && global.initData.takeout.takeout != null){
            takeout = global.initData.takeout.takeout;
        }else{
            takeout = [];
        }

        async.waterfall([
            //通过uid获取用户订单的商品
            function(callback){
                cartM.getProductList(uid,true).then(function(result){
                    var pid;
                    var psid;
                    var specArray;
                    var cid;
                    var imgArray;
                    var mold = '0';
                    var pro_num = 0;

                    if (result.rows > 0) {
                        for (x in result.data) {
                            pid = result.data[x].get('pid'); //读取购物车单条数据的商品ID
                            psid = result.data[x].get('psid'); //读取购物车单条数据的商品规格ID
                            pro_num = result.data[x].get('number');

                            if(parseInt(pro_num) <= 0){
                                return callback({code:506});   //code:506 购买商品数量为0
                            }

                            mold = result.data[x].get('mold'); //
                            specArray = result.data[x].get('product').get('spec'); //读取商品规格数组
                            cid = result.data[x].get('product').get('cid'); //读取商品的分类编号
                            imgArray = JSON.parse(result.data[x].get('product').get('picurlarray'));//读取商品图片数组
                            goods.push(
                                {
                                    pid:        pid,
                                    pname:      result.data[x].get('product').get('name'),
                                    sid:        psid,
                                    cid:        cid,
                                    sname:      specArray[psid]['name'],
                                    price:      parseInt(specArray[psid]['grprice']),
                                    size:       parseInt(result.data[x].get('number')),
                                    img:        imgArray[0],
                                    point:      specArray[psid]['point'],
                                    pointRate:  specArray[psid]['pointRate'],
                                    isPoint:    specArray[psid]['isPoint'],
                                    isDiscount: specArray[psid]['isDiscount']
                                }
                            );

                            if(mold == '0' || mold == '4'){
                                je0 = je0 + (parseInt(specArray[psid]['grprice']) * parseInt(result.data[x].get('number')));
                            }

                            if (pid =="310"||pid =="692"||pid =="693"||pid =="694") {
                                /*赠品~2015-12-12*/
                                goods3.push(
                                    {
                                        pid: pid,
                                        pname: result.data[x].get('product').get('name'),
                                        sid: psid,
                                        cid: cid,
                                        sname: specArray[psid]['name'],
                                        price: parseInt(specArray[psid]['grprice']),
                                        size: parseInt(result.data[x].get('number')),
                                        img: imgArray[0],
                                        point: specArray[psid]['point'],
                                        pointRate: specArray[psid]['pointRate'],
                                        isPoint: specArray[psid]['isPoint'],
                                        isDiscount: specArray[psid]['isDiscount']
                                    }
                                );
                            } else {

                                if(takeout.indexOf(cid)==-1){
                                    //水果类商品
                                    goods1.push(
                                        {
                                            pid:        pid,
                                            pname:      result.data[x].get('product').get('name'),
                                            sid:        psid,
                                            cid:        cid,
                                            sname:      specArray[psid]['name'],
                                            price:      parseInt(specArray[psid]['grprice']),
                                            size:       parseInt(result.data[x].get('number')),
                                            img:        imgArray[0],
                                            point:      specArray[psid]['point'],
                                            pointRate:  specArray[psid]['pointRate'],
                                            isPoint:    specArray[psid]['isPoint'],
                                            isDiscount: specArray[psid]['isDiscount']
                                        }
                                    );

                                    if(mold == '0' || mold == '4'){
                                        je1 = je1 + (parseInt(specArray[psid]['grprice']) * parseInt(result.data[x].get('number')));
                                        points1 = points1+(parseInt(specArray[psid]['point']) * parseInt(result.data[x].get('number')));
                                        yxRebate1 = yxRebate1+(parseInt(specArray[psid]['grprice']) * parseInt(result.data[x].get('number')) * parseInt((specArray[psid]['yxRate']||0)) / 100);

                                        if(specArray[psid]['isDiscount'] == '1'){
                                            dzje1 = dzje1 + (parseInt(specArray[psid]['grprice']) * parseInt(result.data[x].get('number')));
                                        }
                                    }
                                }else{
                                    //非水果类商品
                                    goods2.push(
                                        {
                                            pid:        pid,
                                            pname:      result.data[x].get('product').get('name'),
                                            sid:        psid,
                                            cid:        cid,
                                            sname:      specArray[psid]['name'],
                                            price:      parseInt(specArray[psid]['grprice']),
                                            size:       parseInt(result.data[x].get('number')),
                                            img:        imgArray[0],
                                            point:      specArray[psid]['point'],
                                            pointRate:  specArray[psid]['pointRate'],
                                            isPoint:    specArray[psid]['isPoint'],
                                            isDiscount: specArray[psid]['isDiscount']
                                        }
                                    );

                                    if(mold == '0' || mold == '4'){
                                        points2 = points2+(parseInt(specArray[psid]['point']) * parseInt(result.data[x].get('number')));
                                        yxRebate2 = yxRebate2+(parseInt(specArray[psid]['grprice']) * parseInt(result.data[x].get('number')) * parseInt((specArray[psid]['yxRate']||0)) / 100);

                                        if(specArray[psid]['isDiscount'] == '1'){
                                            dzje2 = dzje2 + (parseInt(specArray[psid]['grprice']) * parseInt(result.data[x].get('number')));
                                        }
                                    }
                                }
                            }
                        }
                        callback(null,result);
                    }else{
                        callback({code:505});   //code:505 购物车内已无商品，请刷新页面
                    }
                });
            },
            //获取该订单是否活动订单
            function(result,callback){

                    var p_id = result.data[0].get('pid')+'';
                    var s_id = result.data[0].get('psid')+'';
                    var c_id =result.data[0].get('product').get('cid');

                    commonM.getLimitCondition(s_id,p_id,c_id,uid).then(function(mm){

                        var normalProduct = mm.finalResult.normalProduct;
                        var isInDate = mm.finalResult.isInDate;
                        var isLoop = mm.finalResult.isLoop;
                        var isInTime = mm.finalResult.isInTime;
                        //console.log(mm.finalResult);

                        if(normalProduct == 0 && isInDate == 1){
                            if(isLoop == 1){
                                if(isInTime == 1){
                                    type = 5;           //预售商品
                                    code = mm.finalResult.actInfo.get('code');
                                }else{
                                    type = 0;           //活动商品,但不在规定时间内
                                }
                            }else{
                                type = 5;           //活动商品
                                code = mm.finalResult.actInfo.get('code');
                            }
                        }else{
                            type = 0;           //正常商品
                        }
                        callback(null,mm);
                    }).catch(function(err){
                        callback({code:9999,reason:err});   //code:9999 系统错误
                    });
            },
            //通过用户地址编号获取用户地址
            function(actInfo,callback){
                addrM.getAddressByObjId(data.addrId).then(function(obj){
                    callback(null,obj,actInfo);
                }).catch(function(err){
                    callback({code:9999,reason:err});   //code:9999 系统错误
                });
            },
            //生成订单1
            function(obj,actInfo,callback){

                var je1_rate = 0;
                if(je0 == 0){
                    je1_rate = 0;
                }else{
                    je1_rate = parseFloat(je1/je0);
                }
                var je2_rate = 1-je1_rate;
                var jsontext = "";

                if(type == 5 && code == 'zqys'){
                    //预售活动
                    type = 5;
                    orderid = 'A'+timestamp;
                }else{
                    type = 0;
                    orderid = 'O'+timestamp;
                }

                if (goods1.length == 0 && goods2.length == 0 && goods3.length > 0) {
                    //只有赠品的订单  2015-12-12
                    data['goods'] = goods3;
                    data['dzje'] = 0;
                    data['point'] = 0;
                    data['psRebate'] = 1;
                    data['yxRebate'] = 0;
                    data['finalAmount'] = 0;
                    data['total'] = 0;
                    data['balance'] = 0;
                    data['online'] = 0;
                    data['type'] = 5;

                    orderid = 'O' + timestamp;

                    data['description'] = str + ':0 元';

                    jsontext = '[{"way":"' + str + '","pay":0}]';

                } else if (goods1.length == 0 && goods2.length > 0) {
                    //只有非水果商品的订单
                    data['goods']=goods2;
                    data['dzje']=dzje2;
                    data['point']=points2;
                    data['psRebate']=1;
                    data['yxRebate']=yxRebate2;
                    data['finalAmount']=parseFloat(parseFloat(finalAmount*je2_rate).toFixed(2));
                    data['total']=parseFloat(parseFloat(total*je2_rate).toFixed(2));
                    data['balance']=parseFloat(parseFloat(balance*je2_rate).toFixed(2));
                    data['online']=parseFloat(parseFloat(online*je2_rate).toFixed(2));
                    data['type']=6;

                    orderid = 'W'+timestamp;

                    if(par>0){
                        data['description']=str+':'+parseFloat(finalAmount*je2_rate).toFixed(2)+' 元,优惠券抵扣:'+parseFloat(par*je2_rate).toFixed(2)+'元';
                    }else{
                        data['description']=str+':'+parseFloat(finalAmount*je2_rate).toFixed(2)+' 元';
                    }

                    jsontext = '[{"way":"'+str+'","pay":'+parseFloat(finalAmount*je2_rate).toFixed(2)+'}]';

                }else{
                    data['goods']=goods1;
                    data['dzje']=dzje1;
                    data['point']=points1;
                    data['psRebate']=1;
                    data['yxRebate']=yxRebate1;
                    data['finalAmount']=parseFloat(parseFloat(finalAmount*je1_rate).toFixed(2));
                    data['total']=parseFloat(parseFloat(total*je1_rate).toFixed(2));
                    data['balance']=parseFloat(parseFloat(balance*je1_rate).toFixed(2));
                    data['online']=parseFloat(parseFloat(online*je1_rate).toFixed(2));
                    data['type']=type;

                    if(par>0){
                        data['description']=str+':'+parseFloat(finalAmount*je1_rate).toFixed(2)+' 元,优惠券抵扣:'+parseFloat(par*je1_rate).toFixed(2)+'元';
                    }else{
                        data['description']=str+':'+parseFloat(finalAmount*je1_rate).toFixed(2)+' 元';
                    }

                    jsontext = '[{"way":"'+str+'","pay":'+parseFloat(finalAmount*je1_rate).toFixed(2)+'}]';
                }

                if ((goods1.length > 0 && goods2.length > 0) || (goods2.length > 0 && goods3.length > 0) || (goods1.length > 0 && goods3.length > 0)) {
                    data['orderid'] = orderid + "-1";
                    //data['oid']=order_id;
                } else {
                    data['orderid'] = orderid;
                    //data['oid']=orderid;
                }

                data['oid']=order_id;
                data['payway']=str;
                data['uid']=uid;
                data['onlinetype']=onlinetype;
                data['status']=status;
                data['canceltime']=timestamp+(2*60*60);
                data['address']=obj.toJSON();
                data['details']=JSON.parse(jsontext);

                if(str=="微信支付"){
                    data['syncStatus']=0;
                }else {
                    data['syncStatus']=1;
                    data['paytime']=timestamp;
                }

                data['location']= new AV.GeoPoint({latitude: 39.9, longitude: 116.4});

                orderM.addOrder(data).then(function(result){
                    //保存成功
                    callback(null,obj,actInfo,je1_rate,je2_rate);
                }).catch(function(err){
                    //保存失败
                    callback({code:9999,reason:err});   //code:9999 系统错误
                });
            },
            //生成订单2
            function(obj,actInfo,je1_rate,je2_rate,callback){

                if(goods1.length == 0 || goods2.length == 0){
                    callback(null,obj,actInfo);
                }else{
                    data['payway']=str;

                    if(par>0){
                        data['description']=str+':'+parseFloat(finalAmount*je2_rate).toFixed(2)+' 元,优惠券抵扣:'+parseFloat(par*je2_rate).toFixed(2)+'元';
                    }else{
                        data['description']=str+':'+parseFloat(finalAmount*je2_rate).toFixed(2)+' 元';
                    }

                    data['uid']=uid;
                    data['finalAmount']=parseFloat(parseFloat(finalAmount*je2_rate).toFixed(2));
                    data['total']=parseFloat(parseFloat(total*je2_rate).toFixed(2));
                    data['dzje']=dzje2;
                    data['balance']=parseFloat(parseFloat(balance*je2_rate).toFixed(2));
                    data['online']=parseFloat(parseFloat(online*je2_rate).toFixed(2));
                    data['onlinetype']=onlinetype;
                    data['type']=6;
                    orderid = 'W'+timestamp;
                    data['orderid']=orderid+"-2";
                    data['oid']=order_id;
                    data['status']=status;
                    data['point']=points2;
                    data['psRebate']=1;
                    data['yxRebate']=yxRebate2;
                    data['canceltime']=timestamp+(2*60*60);
                    data['goods']=goods2;
                    data['address']=obj.toJSON();
                    var jsontext = '[{"way":"'+str+'","pay":'+parseFloat(finalAmount*je2_rate).toFixed(2)+'}]';
                    data['details']=JSON.parse(jsontext);

                    if(str=="微信支付"){
                        data['syncStatus']=0;
                    }else {
                        data['syncStatus']=1;
                        data['paytime']=timestamp;
                    }

                    data['location']= new AV.GeoPoint({latitude: 39.9, longitude: 116.4});

                    orderM.addOrder(data).then(function (result1) {
                        //保存成功
                        callback(null,obj,actInfo);
                    }).catch(function (err) {
                        //保存失败
                        callback({code: 9999, reason: err});   //code:9999 系统错误
                    });
                }
            },

            /*************生成订单3   2015-12-12********************/
            function (obj,actInfo,callback) {

                if (goods1.length == 0||goods3.length == 0) {
                    callback(null, actInfo);
                } else {
                    data['payway'] = str;
                    data['description'] = str + ':0 元';

                    data['uid'] = uid;
                    data['finalAmount'] = 0;
                    data['total'] = 0;
                    data['dzje'] = 0;
                    data['balance'] = 0;
                    data['online'] = 0;
                    data['onlinetype'] = onlinetype;
                    data['type'] = 5;
                    orderid = 'O' + timestamp;
                    data['orderid'] = orderid + "-3";
                    data['oid'] = order_id;
                    data['status'] = status;
                    data['point'] = 0;
                    data['psRebate'] = 1;
                    data['yxRebate'] = 0;
                    data['canceltime'] = timestamp + (2 * 60 * 60);
                    data['goods'] = goods3;
                    data['address'] = obj.toJSON();
                    var jsontext3 = '[{"way":"' + str + '","pay":0}]';
                    data['details'] = JSON.parse(jsontext3);
                    data['location'] = new AV.GeoPoint({latitude: 39.9, longitude: 116.4});
                    orderM.addOrder(data).then(function(obj){
                        //保存成功
                        callback(null,actInfo);
                    }).catch(function(err){
                        //保存失败
                        callback({code:9999,reason:err});   //code:9999 系统错误
                    });
                }
            },
            //向limitbuyrecord表中插入数据
            function(actInfo,callback){

                var normalProduct = actInfo.finalResult.normalProduct;
                var isInDate = actInfo.finalResult.isInDate;
                var isLoop = actInfo.finalResult.isLoop;
                var isInTime = actInfo.finalResult.isInTime;
                if(normalProduct == 0 && isInDate == 1){
                    if(isLoop == 1){
                        if(isInTime == 1){
                            orderM.addToLimitRecord(uid,order_id,goods[0].pid,goods[0].sid,goods[0].cid,actInfo.finalResult.actInfo.id).then(function(res){

                                return callback(null);
                            }).catch(function(err){
                                callback(err);
                            });
                        }else{
                            return callback(null);
                        }
                    }else{
                        orderM.addToLimitRecord(uid,order_id,goods[0].pid,goods[0].sid,goods[0].cid,actInfo.finalResult.actInfo.id).then(function(res){

                            //console.log("向limitbuyrecord表中插入数据----end");
                            return callback(null);
                        }).catch(function(err){
                            callback(err);
                        });
                    }
                }else{
                    callback(null);
                }

            },
            //更新用户余额
            function(callback){
                if(payway =='ye_pay' && finalAmount > 0){
                    UserM.minusAmount(uid,finalAmount*100).then(function(result){

                        callback(null,result.ysye,result.dqye);
                    }).catch(function(err){
                        callback({code:9999,reason:err});   //code:9999 系统错误
                    });
                }else{
                    callback(null,0,0);
                }
            },
            //更新用户余额流水
            function(ysye,dqye,callback){
                if(payway =='ye_pay' && finalAmount > 0){
                    var amountflow = new AmountFlowM();
                    amountflow.set('newamount',finalAmount);
                    amountflow.set('beforeamount',ysye);
                    amountflow.set('afteramount',dqye);
                    amountflow.set('userid',uid);
                    amountflow.set('content','订单'+order_id+'使用余额支付,扣除账户余额'+finalAmount+'元.');
                    amountflow.save().then(function(result){
                        callback(null);
                    }).catch(function(err){
                        callback({code:9999,reason:err});//code:9999 系统错误
                    });
                }else{
                    callback(null);
                }
            },
            //删除购物车商品
            function(callback){
                cartM.delCart(uid).then(function(result){
                    callback(null);
                }).catch(function(err){
                    callback({code:9999,reason:err});   //code:9999 系统错误
                });               　
            },

            //生成流水信息
            function(callback){
                if(payway =='ye_pay' || payway =='hdfk_pay'){
                    var flow = new FlowM();
                    flow.set('orderid',order_id);
                    flow.set('amount',finalAmount);
                    flow.set('paytime',new Date().getTime());
                    flow.set('userid',uid);
                    flow.set('content','使用'+str+finalAmount+'元.');
                    flow.save().then(function(result){
                        callback(null);
                    }).catch(function(err){
                        callback({code:9999,reason:err});//code:9999 系统错误
                    });
                }else{
                    callback(null);
                }
            },

            //更新优惠券使用状态
            function(callback){
                if(!couponId){
                    callback(null,{code:0,orderid:order_id,fee:finalAmount*100});
                }else{
                    CouponM.updateUserCoupon(couponId,1).then(function(result){
                        callback(null,{code:0,orderid:order_id,fee:finalAmount*100});
                    }).catch(function(err){
                        callback({code:9999,reason:err});   //code:9999 系统错误
                    });
                }
            }
        ],function(err,result){
            if(err){
                res.json(err);
            }
            res.json(result);
        });
    },
    /**
     * 微信支付回调接口
     * Created by James at 2015-09-10
     * @param req
     * @param res
     * @param next
     */
    notify:function(req,res,next){
        var data = req.query;//获取表单参数

        var orderid = data.orderid;
        var je = parseInt(data.je+"")*100;
        var payWay = data.payWay;

        orderM.notify(orderid,je,payWay).then(function(order){
            res.render('order/myOrderByAll',{title:'我的全部订单',order:order});
        }).catch(function(err){
            res.error(err);
        });

        async.waterfall([
            //微信支付回调接口
            function(callback){
                orderM.notify(orderid,je,payWay).then(function(obj){
                    callback(null,obj.userid,obj.point,je);
                }).catch(function(err){
                    callback({code:9999,reason:err});   //code:9999 系统错误
                });
            },
            //更新用户余额
            function(userid,point,je,callback){
                UserM.minusAmount(uid,je).then(function(result){
                    callback(null,uid,point);
                }).catch(function(err){
                    callback({code:9999,reason:err});   //code:9999 系统错误
                });
            },
            //更新用户积分
            function(userid,point,callback){
                UserM.updatePoints(userid,point).then(function(result){
                    callback(null,{code:0});
                }).catch(function(err){
                    callback({code:9999,reason:err});   //code:9999 系统错误
                });
            }
        ],function(err,result){
            if(err){
                res.json(err);
            }
            res.json(result);
        });
    },
    setOrderCancel:function(req,res,next){
        //撤销订单

        var objectId = req.params.objectId;         //获取objectId

        orderM.setOrderCancel(objectId).then(function(order){
            res.redirect('/user/history/0');
        }).catch(function(err){
            res.json(err);
        });
    },
    againPay:function(req,res,next){
        //订单重新付款

        var data = req.query;//获取表单参数

        var orderid = data.orderid;             //获取订单编号
        var payWay = data.payway;               //获取支付方式

        orderM.againPay(orderid,payWay).then(function(result){
            res.json(result);
        }).catch(function(err){
            res.json(err);
        });
    },
    /**
     * 跳转到套餐确认订单页面
     * Created by James at 2015-10-13
     * @param req
     * @param res
     * @param next
     */
    confirmPackageOrder:function(req,res,next){

        var userid = req.AV.user.id;              //获取用户编号
        var openid = req.AV.user.get('openid');   //获取openid

        var aid = req.params.aid;           //用户地址编号
        var total = req.params.total;
        var isPackage = req.params.isPackage;

        if(!total){
            total = 10;
        }

        if(!isPackage){
            isPackage = 0;
        }

        console.log("=======================isPackage123");
        console.log(isPackage);


        var goods = [];

        if(aid == 0){
            //用户地址为空，代表是从购物车模块跳转过来的
            AddrM.listAddress(userid).then(function(obj){
                if(obj.length == 0){
                    //没有地址，则跳转到新增地址页面
                    var url = '/order/confirmPackageOrder/';
                    res.redirect('/user/center/address?back='+url);
                }else{
                    async.waterfall([
                        //通过userid获取用户订单的商品
                        function(callback){
                            cartM.getPackageProductList(userid).then(function(result){
                                var psid;
                                var specArray;
                                var imgArray;
                                var price;
                                if (result.rows > 0) {
                                    for (x in result.data) {
                                        psid = result.data[x].get('psid'); //读取购物车单条数据的商品规格ID
                                        specArray = result.data[x].get('product').get('spec'); //读取商品规格数组
                                        imgArray = JSON.parse(result.data[x].get('product').get('picurlarray'));//读取商品图片数组

                                        if(isPackage == 19){
                                            price = parseInt(result.data[x].get('packagePrice'))
                                        }else{
                                            price = parseInt(result.data[x].get('price'))
                                        }

                                        console.log('---------------------------');
                                        console.log(result.data[x]);

                                        goods.push(
                                            {
                                                pname:      result.data[x].get('product').get('name'),
                                                sname:      specArray[psid]['name'],
                                                price:      price,
                                                size:       result.data[x].get('count'),
                                                img:        imgArray[0]
                                            }
                                        )
                                    }
                                }
                                callback(null);
                            });
                        },
                        //获取用户余额
                        function(callback){
                            UserM.getAmountByOpenID(openid).then(function (balance) {
                                callback(null,{cartList:goods,total:total,balance:balance});
                            }).catch(function(err){
                                callback({code:9999,reason:err});   //code:9999 系统错误
                            });
                        }
                    ],function(err,result){
                        if(err){
                            res.error(err);
                        }
                        if(result.cartList.length == 0){
                            //如果没有商品，则跳转到首页
                            res.redirect('/');
                        }else{
                            res.render('order/confirmPackageOrder',{title:'确认订单',cart:result.cartList,total:result.total,balance:result.balance,aid:aid,isPackage:isPackage});
                        }
                    });
                }
            }).catch(function(err){
                res.error(err);
            });
        }else{
            //用户地址不为空，代表是从我的地址模块跳转过来的
            async.waterfall([
                //通过userid获取用户订单的商品
                function(callback){
                    cartM.getPackageProductList(userid).then(function(result){
                        var psid;
                        var specArray;
                        var imgArray;
                        if (result.rows > 0) {
                            for (x in result.data) {
                                psid = result.data[x].get('psid'); //读取购物车单条数据的商品规格ID
                                specArray = result.data[x].get('product').get('spec'); //读取商品规格数组
                                imgArray = JSON.parse(result.data[x].get('product').get('picurlarray'));//读取商品图片数组
                                goods.push(
                                    {
                                        pname:      result.data[x].get('product').get('name'),
                                        sname:      specArray[psid]['name'],
                                        price:      parseInt(specArray[psid]['packageprice']),
                                        size:       parseInt(result.data[x].get('count')),
                                        img:        imgArray[0]
                                    }
                                )
                            }
                        }
                        callback(null);
                    });
                },
                //获取用户余额
                function(callback){
                    UserM.getAmountByOpenID(openid).then(function (balance) {
                        callback(null,{cartList:goods,total:total,balance:balance});
                    }).catch(function(err){
                        callback({code:9999,reason:err});   //code:9999 系统错误
                    });
                }
            ],function(err,result){
                if(err){
                    res.error(err);
                }

                if(result.cartList.length == 0){
                    //如果没有商品，则跳转到首页
                    res.redirect('/');
                }else{
                    res.render('order/confirmPackageOrder',{title:'确认订单',cart:result.cartList,total:result.total,balance:result.balance,aid:aid,isPackage:isPackage});
                }
            });
        }
    },
    confirmPackageOrderUI:function(req,res,next){
        //确认订单
        res.render('order/confirmPackageOrder',{title:'确认订单'});
    },
    /**
     * 生成订单
     * Created by James at 2015-10-13
     * @param req
     * @param res
     * @param next
     */
    addPackageOrder:function(req,res,next){
        var data = req.query;//获取表单参数

        var total = parseFloat(parseFloat(data.total).toFixed(2));

        var isPackage = data.isPackage;

        if(!isPackage){
            isPackage = 0;
        }

        delete data.isPackage;

        var payway = data.payway;
        var type = 0;           //0:普通订单 5：预售订单
        var str ;
        var balance = 0;
        var online = 0;
        var onlinetype = '';
        var status = 1000;
        var dzje = 0;
        var points = 0;
        var yxRebate = 0;           //营销提成


        if(payway =='ye_pay'){
            console.log('===================余额支付');
            str = '余额支付';
            balance = total;
            status = 2000;

        }else if(payway =='wx_pay'){
            console.log('===================微信支付');
            str = '微信支付';
            online = total;
            onlinetype = '微信支付';
            status = 1000;
        }else{
            console.log('===================货到付款');
            //payway =='hdfk_pay'
            str = '货到付款';
            status = 2000;
        }

        console.log('===================');
        console.log(payway);
        console.log(str);

        var uid = req.AV.user.id;
        var goods = new Array();
        var timestamp=new Date().getTime();
        var orderid = 'P'+timestamp;

        console.log('===========orderid:'+orderid);

        async.waterfall([
            //通过uid获取用户订单的商品
            function(callback){
                console.log('===========1');
                cartM.getPackageProductList(uid).then(function(result){
                    var pid;
                    var psid;
                    var specArray;
                    var cid;
                    var imgArray;
                    var mold = '0';
                    var price;

                    var pro_num = 0;

                    if (result.rows > 0) {
                        for (x in result.data) {
                            pid = result.data[x].get('pid'); //读取购物车单条数据的商品ID
                            psid = result.data[x].get('psid'); //读取购物车单条数据的商品规格ID
                            pro_num = result.data[x].get('count');

                            if(parseInt(pro_num) <= 0){
                                return callback({code:506});   //code:506 购买商品数量为0
                            }

                            mold = result.data[x].get('mold'); //
                            specArray = result.data[x].get('product').get('spec'); //读取商品规格数组
                            cid = result.data[x].get('product').get('cid'); //读取商品的分类编号
                            imgArray = JSON.parse(result.data[x].get('product').get('picurlarray'));//读取商品图片数组

                            if(isPackage == 19){
                                price = parseInt((specArray[psid]['packageprice']||0));
                            }else{
                                price = parseInt((specArray[psid]['grprice']||0));
                            }

                            goods.push(
                                {
                                    pid:        pid,
                                    pname:      result.data[x].get('product').get('name'),
                                    sid:        psid,
                                    cid:        cid,
                                    sname:      specArray[psid]['name'],
                                    price:      price,
                                    size:       parseInt(result.data[x].get('count')),
                                    img:        imgArray[0],
                                    point:      specArray[psid]['point'],
                                    pointRate:  specArray[psid]['pointRate'],
                                    isPoint:    specArray[psid]['isPoint'],
                                    isDiscount: specArray[psid]['isDiscount']
                                }
                            );

                            if(mold == '0' || mold == '4'){
                                points = points+(parseInt(specArray[psid]['point']) * parseInt(result.data[x].get('count')));
                                yxRebate = yxRebate+(parseInt((specArray[psid]['packageprice']||0)) * parseInt(result.data[x].get('number')) * parseInt((specArray[psid]['yxRate']||0)) / 100);
                            }

                            if(specArray[psid]['isDiscount'] == '1'){
                                dzje = dzje + (parseInt(specArray[psid]['packageprice']) * parseInt(result.data[x].get('count')));
                            }

                        }
                        callback(null);
                    }else{
                        callback({code:505});   //code:505 购物车内已无商品，请刷新页面
                    }
                });
            },
            //通过用户地址编号获取用户地址
            function(callback){
                console.log('===========2');
                addrM.getAddressByObjId(data.addrId).then(function(obj){
                    callback(null,obj);
                }).catch(function(err){
                    callback({code:9999,reason:err});   //code:9999 系统错误
                });
            },
            //生成订单
            function(obj,callback){
                console.log('===========3');
                data['goods']=goods;
                data['dzje']=dzje;
                data['point']=points;
                data['finalAmount']=total;
                data['total']=total;
                data['balance']=parseFloat(parseFloat(balance).toFixed(2));
                data['online']=parseFloat(parseFloat(online).toFixed(2));
                data['type']=6;
                data['description']=str+':'+total+' 元';
                data['orderid']=orderid;
                data['oid']=orderid;
                data['payway']=str;
                data['psRebate']=1;
                data['yxRebate']=yxRebate;
                data['uid']=uid;
                data['onlinetype']=onlinetype;
                data['status']=status;
                data['canceltime']=timestamp+(2*60*60);
                data['address']=obj.toJSON();
                var jsontext = '[{"way":"'+str+'","pay":'+total+'}]';
                data['details']=JSON.parse(jsontext);

                if(str=="微信支付"){
                    data['syncStatus']=0;
                }else {
                    data['syncStatus']=1;
                    data['paytime']=timestamp;
                }

                data['location']= new AV.GeoPoint({latitude: 39.9, longitude: 116.4});

                orderM.addOrder(data).then(function(result){
                    //保存成功
                    callback(null);
                }).catch(function(err){
                    //保存失败
                    callback({code:9999,reason:err});   //code:9999 系统错误
                });
            },
            //更新用户余额
            function(callback){
                console.log('===========4');
                if(payway =='ye_pay'){
                    UserM.minusAmount(uid,total*100).then(function(result){
                        callback(null,result.ysye,result.dqye);
                    }).catch(function(err){
                        callback({code:9999,reason:err});   //code:9999 系统错误
                    });
                }else{
                    callback(null,0,0);
                }
            },
            //更新用户余额流水
            function(ysye,dqye,callback){
                console.log('===========5');
                if(payway =='ye_pay'){
                    var amountflow = new AmountFlowM();
                    amountflow.set('newamount',total);
                    amountflow.set('beforeamount',ysye);
                    amountflow.set('afteramount',dqye);
                    amountflow.set('userid',uid);
                    amountflow.set('content','订单'+orderid+'使用余额支付,扣除账户余额'+total+'元.');
                    amountflow.save().then(function(result){
                        callback(null);
                    }).catch(function(err){
                        callback({code:9999,reason:err});//code:9999 系统错误
                    });
                }else{
                    callback(null);
                }
            },
            //删除购物车商品
            function(callback){
                console.log('===========6');
                cartM.delPackageCart(uid).then(function(result){
                    callback(null);
                }).catch(function(err){
                    callback({code:9999,reason:err});   //code:9999 系统错误
                });
            },

            //生成流水信息
            function(callback){
                console.log('===========7');
                if(payway =='ye_pay' || payway =='hdfk_pay'){
                    var flow = new FlowM();
                    flow.set('orderid',orderid);
                    flow.set('amount',total);
                    flow.set('paytime',new Date().getTime());
                    flow.set('userid',uid);
                    flow.set('content','使用'+str+total+'元.');
                    flow.save().then(function(result){
                        callback(null,{code:0,orderid:orderid,fee:total*100});
                    }).catch(function(err){
                        callback({code:9999,reason:err});//code:9999 系统错误
                    });
                }else{
                    callback(null,{code:0,orderid:orderid,fee:total*100});
                }
            }
        ],function(err,result){
            console.log('===========8');
            if(err){
                console.log('===========9');
                console.log(err);
                res.json(err);
            }
            console.log('===========10');
            res.json(result);
        });
    },
    /**
     * 更新订单状态为待微信回调
     * Created by James at 2015-12-28
     * @param req
     * @param res
     * @param next
     */
    wxwait:function(req,res,next){
        console.log("===========================1");
        var orderid=req.query.orderid;
        console.log("===========================1:"+orderid);
        orderM.wxwait(orderid).then(function(data){
            console.log("===========================11");
            res.json(data);
        }).catch(function(err){
            console.log("===========================12");
            res.json(err);
        });
    },
    /**
     * 充值卡充值
     * Created by James at 2016-01-28
     * @param req
     * @param res
     * @param next
     */
    czkcz:function(req,res,next){
        console.log("===========================1");
        var km=req.query.km;
        console.log("===========================1:"+km);
        var timestamp = new Date().getTime()+"";
        console.log("===========================2:"+timestamp);
        timestamp = timestamp.substr(0,10);
        console.log("===========================3:"+timestamp);
        var uid = req.AV.user.id;
        orderM.czkcz(km,timestamp,uid).then(function(data){
            console.log("===========================11");
            res.json(data);
        }).catch(function(err){
            console.log("===========================12");
            res.json(err);
        });
    }
};